/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2020年9月5日
 */
package com.massyframework.beanskin.runtime.modular.assembly.handling;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.massyframework.beanskin.assembly.Assembly;
import com.massyframework.beanskin.assembly.beans.BeanContextHandlerFactory;
import com.massyframework.beanskin.assembly.beans.BeanRegistry;
import com.massyframework.beanskin.assembly.handling.LifecycleManager;


/**
 * 生命周期管理器工厂
 * @author huangkh
 *
 */
public abstract class LifecycleManagerFactory {
	
	private static final Logger LOG = LoggerFactory.getLogger(LifecycleManagerFactory.class);

	/**
	 * 创建装配件的生命周期管理
	 * @param assembly {@link ServiceExportableModule}
	 * @param builder {@link DefaultAssemblyBuilder}
	 * @return {@link LifecycleManager}
	 */
	public static LifecycleManager createLifecycleManager(Assembly assembly, 
			List<Object> handlers, Map<String, Object> beanMap, BeanContextHandlerFactory factory,
			boolean hasDependencies, boolean hasExports) {
		DefaultLifecycleManager result = new DefaultLifecycleManager(assembly);
		
		if (handlers != null) {
			handlers.forEach( h -> {
				try {
					result.register(h);
				} catch (Exception e) {
					if (LOG.isErrorEnabled()) {
						LOG.error(e.getMessage(), e);
					}
				}
			});
		}
			
		if (hasExports) {
			try {
				result.register(new ServiceExporter());
			} catch (Exception e) {
				if (LOG.isErrorEnabled()) {
					LOG.error(e.getMessage(), e);
				}
			}
		}
				
		if (hasDependencies) {
			try {
				result.register(new DependentOnMatching());
				result.register(new DefaultDependencyMatcher());
			} catch (Exception e) {
				if (LOG.isErrorEnabled()) {
					LOG.error(e.getMessage(), e);
				}
			}
		}
		
		if (factory != null) {
			try {
				Object handler = factory.createBeanContextHandler(assembly);
				result.register(handler);
				if (handler instanceof BeanRegistry) {
					BeanRegistry registry = (BeanRegistry)handler;
					for (Map.Entry<String, Object> entry: beanMap.entrySet()) {
						registry.addBean(entry.getKey(), entry.getValue());
					}
				}
			} catch (Exception e) {
				if (LOG.isErrorEnabled()) {
					LOG.error(e.getMessage(), e);
				}
			}
		}
		
		return result;
	}

}
